/**
 * Copyright 2020 OPSLI 快速开发平台 https://www.opsli.com
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.opsli.modulars.business.valveStation.web;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.opsli.api.web.business.patrolStation.PatrolStationRestApi;
import org.opsli.api.web.business.valveStation.ValveStationRestApi;
import org.opsli.api.wrapper.business.emergency.EmergencyReportModel;
import org.opsli.api.wrapper.business.patrolLocation.PatrolLocationModel;
import org.opsli.api.wrapper.business.patrolStation.PatrolStationModel;
import org.opsli.api.wrapper.business.valveStation.ValveStationModel;
import org.opsli.api.wrapper.system.org.SysOrgModel;
import org.opsli.api.wrapper.system.user.UserModel;
import org.opsli.common.annotation.RequiresPermissionsCus;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.opsli.api.base.result.ResultVo;
import org.opsli.common.annotation.ApiRestController;
import org.opsli.common.annotation.EnableLog;
import org.opsli.core.base.controller.BaseRestController;
import org.opsli.core.persistence.Page;
import org.opsli.core.persistence.querybuilder.QueryBuilder;
import org.opsli.core.persistence.querybuilder.WebQueryBuilder;
import org.opsli.core.utils.UserUtil;
import org.opsli.modulars.business.app.web.CoordinatesConvertUtil;
import org.opsli.modulars.business.app.web.MapCordinatesVo;
import org.opsli.modulars.business.app.web.ZkUtils;
import org.opsli.modulars.business.patrolDict.entity.PatrolDict;
import org.opsli.modulars.business.patrolDict.service.IPatrolDictService;
import org.opsli.modulars.business.patrolStation.entity.PatrolStationWeb;
import org.opsli.modulars.business.valveStation.entity.ValveStation;
import org.opsli.modulars.business.valveStation.service.IValveStationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

import org.opsli.modulars.business.patrolStation.entity.PatrolStation;
import org.opsli.modulars.business.patrolStation.service.IPatrolStationService;

/**
 * 巡点管理 Controller
 *
 * @author zk
 * @date 2021-09-14 15:53:53
 */
@Api(tags = ValveStationRestApi.TITLE)
@Slf4j
@ApiRestController("/business/valveStation")
public class ValveStationRestController extends BaseRestController<ValveStation, ValveStationModel, IValveStationService>
    implements ValveStationRestApi {

    @Value("${opsli.fileUrl}")
    private  String fileUrl;
    @Autowired
    private IPatrolDictService dictService;

    /**
    * 巡点管理 查一条
    * @param model 模型
    * @return ResultVo
    */
    @ApiOperation(value = "获得单条巡点管理", notes = "获得单条巡点管理 - ID")
   /* @RequiresPermissions("patrolstation_select")*/
    @Override
    public ResultVo<ValveStationModel> get(ValveStationModel model) {
        // 如果系统内部调用 则直接查数据库
        if(model != null && model.getIzApi() != null && model.getIzApi()){
            model = IService.get(model);
        }
        return ResultVo.success(model);
    }

    @Override
    public ResultVo<Map> getOne() {
        Map map=new HashMap();
        String devid=UserUtil.getSysUser().getCompanyId();
        if(devid.equals("41002")){
            map.put("ad","中牟县");
            map.put("city","郑州市");
            map.put("ln","115.273178");
            map.put("lt","30.457733");
        }else{
            map.put("ad","中牟县");
            map.put("city","郑州市");
            map.put("ln","113.326973");
            map.put("lt","34.817928");
        }
        return ResultVo.success(map);
    }




    @Override
    public ResultVo<Map> getFile(String id){
        Map map=new HashMap();
        ValveStationModel model=IService.get(id);
        List<Map> list=new ArrayList<Map>();
        if(ZkUtils.isNotBlank(model.getLastPic())){
            String[] arr=model.getLastPic().split(",");
            for(String s:arr){
                Map datamap=new HashMap();
                datamap.put("src",fileUrl+s);
                list.add(datamap);
            }
        }
        map.put("pic",list);
        if(ZkUtils.isNotBlank(model.getLastVideo())){
            map.put("video", fileUrl+model.getLastVideo());
        }else{
            map.put("video", "");
        }
        return ResultVo.success(map);}


    @Override
    public ResultVo<List<Map>> getListNew(String userId){
        List<Map> maps=new ArrayList<>();
        Map map = new HashMap();
        map.put("lt","1");
        map.put("ln","2");
        maps.add(map);
        return ResultVo.success(maps);


    }

    /**
    * 巡点管理 查询分页
    * @param pageNo 当前页
    * @param pageSize 每页条数
    * @param request request
    * @return ResultVo
    */
    @ApiOperation(value = "获得分页数据", notes = "获得分页数据 - 查询构造器")
    /*@RequiresPermissions("patrolstation_select")*/
    @Override
    public ResultVo<?> findPage(Integer pageNo, Integer pageSize, HttpServletRequest request) {
        Map<String,String[]> queryMap = new LinkedHashMap(request.getParameterMap());
        String devid=UserUtil.getSysUser().getCompanyId();
        if(!devid.equals("123")){
            queryMap.put("devid_EQ",new String[]{devid});
        }
        QueryBuilder<ValveStation> queryBuilder = new WebQueryBuilder<>(entityClazz, queryMap);
        Page<ValveStation, ValveStationModel> page = new Page<>(pageNo, pageSize);
        page.setQueryWrapper(queryBuilder.build());
        page = IService.findPage(page);

        return ResultVo.success(page.getPageData());
    }

    /**
    * 巡点管理 新增
    * @param model 模型
    * @return ResultVo
    */
    @ApiOperation(value = "新增巡点管理数据", notes = "新增巡点管理数据")
    @EnableLog
    @Override
    public ResultVo<?> insert(ValveStationModel model) {
        UserModel user = UserUtil.getSysUser();
        if(user!=null){
            model.setDevid(user.getCompanyId());
            model.setDevname(user.getCompany());
        }
        try {
            MapCordinatesVo cordinatesVo=new MapCordinatesVo();
            cordinatesVo.setLon(new BigDecimal(model.getLongitude()));
            cordinatesVo.setLat(new BigDecimal(model.getDimension()));
            cordinatesVo= CoordinatesConvertUtil.gd_decrypt(cordinatesVo);
            model.setLongitude(cordinatesVo.getLon().toString());
            model.setDimension(cordinatesVo.getLat().toString());
        }catch (Exception e){

        }


        // 调用新增方法
        IService.insert(model);
        return ResultVo.success("新增巡点成功");
    }

    /**
    * 巡点管理 修改
    * @param model 模型
    * @return ResultVo
    */
    @ApiOperation(value = "修改巡点管理数据", notes = "修改巡点管理数据")
    @EnableLog
    @Override
    public ResultVo<?> update(ValveStationModel model) {
        ValveStationModel old=IService.get(model.getId());
        if(ZkUtils.isNotBlank(model.getDimension())&&ZkUtils.isNotBlank(model.getLongitude())){
            if(!model.getDimension().equals(old.getDimension())||!model.getLongitude().equals(old.getLongitude())){
                MapCordinatesVo cordinatesVo=new MapCordinatesVo();
                cordinatesVo.setLon(new BigDecimal(model.getLongitude()));
                cordinatesVo.setLat(new BigDecimal(model.getDimension()));
                cordinatesVo= CoordinatesConvertUtil.gd_decrypt(cordinatesVo);
                model.setLongitude(cordinatesVo.getLon().toString());
                model.setDimension(cordinatesVo.getLat().toString());
            }
        }
        // 调用修改方法
        IService.update(model);
        return ResultVo.success("修改巡点成功");
    }


    /**
    * 巡点管理 删除
    * @param id ID
    * @return ResultVo
    */
    @ApiOperation(value = "删除巡点管理数据", notes = "删除巡点管理数据")
    @EnableLog
    @Override
    public ResultVo<?> del(String id){
        IService.delete(id);
        return ResultVo.success("删除巡点成功");
    }

    /**
    * 巡点管理 批量删除
    * @param ids ID 数组
    * @return ResultVo
    */
    @ApiOperation(value = "批量删除巡点管理数据", notes = "批量删除巡点管理数据")
    @EnableLog
    @Override
    public ResultVo<?> delAll(String ids){
        String[] idArray = Convert.toStrArray(ids);
        IService.deleteAll(idArray);
        return ResultVo.success("批量删除巡点管理成功");
    }


    /**
    * 巡点管理 Excel 导出
    * 注：这里 RequiresPermissionsCus 引入的是 自定义鉴权注解
    *
    * 导出时，Token认证和方法权限认证 全部都由自定义完成
    * 因为在 导出不成功时，需要推送错误信息，
    * 前端直接走下载流，当失败时无法获得失败信息，即使前后端换一种方式后端推送二进制文件前端再次解析也是最少2倍的耗时
    * ，且如果数据量过大，前端进行渲染时直接会把浏览器卡死
    * 而直接开启socket接口推送显然是太过浪费资源了，所以目前采用Java最原始的手段
    * response 推送 javascript代码 alert 提示报错信息
    *
    * @param request request
    * @param response response
    */
    @ApiOperation(value = "导出Excel", notes = "导出Excel")
    @RequiresPermissionsCus("patrolstation_export")
    @EnableLog
    @Override
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        // 当前方法
        Method method = ReflectUtil.getMethodByName(this.getClass(), "exportExcel");
        QueryBuilder<ValveStation> queryBuilder = new WebQueryBuilder<>(entityClazz, request.getParameterMap());
        super.excelExport(PatrolStationRestApi.SUB_TITLE, queryBuilder.build(), response, method);
    }

    /**
    * 巡点管理 Excel 导入
    * 注：这里 RequiresPermissions 引入的是 Shiro原生鉴权注解
    * @param request 文件流 request
    * @return ResultVo
    */
    @ApiOperation(value = "导入Excel", notes = "导入Excel")
    @RequiresPermissions("patrolstation_import")
    @EnableLog
    @Override
    public ResultVo<?> importExcel(MultipartHttpServletRequest request) {
        return super.importExcel(request);
    }

    /**
    * 巡点管理 Excel 下载导入模版
    * 注：这里 RequiresPermissionsCus 引入的是 自定义鉴权注解
    * @param response response
    */
    @ApiOperation(value = "导出Excel模版", notes = "导出Excel模版")
    @RequiresPermissionsCus("patrolstation_import")
    @Override
    public void importTemplate(HttpServletResponse response) {
        // 当前方法
        Method method = ReflectUtil.getMethodByName(this.getClass(), "importTemplate");
        super.importTemplate(PatrolStationRestApi.SUB_TITLE, response, method);
    }

    @Override
    public void getImages(HttpServletRequest request,HttpServletResponse response){
        InputStream fis = null;
        OutputStream os = null ;
        URL url = null;
        HttpURLConnection httpUrl = null;
        String path = request.getParameter("path");
        try {
            fis = new FileInputStream(path);
            os = response.getOutputStream();
            int count = 0;
            byte[] buffer = new byte[1024 * 8];
            while ((count = fis.read(buffer)) != -1) {
                os.write(buffer, 0, count);
                os.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
                os.close();
//                httpUrl.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
